package com.monitoring.infrastructure.persistence;

import com.monitoring.domain.entity.EnvironmentalData;
import com.monitoring.domain.repository.EnvironmentalDataRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface JpaEnvironmentalDataRepository extends JpaRepository<EnvironmentalData, Long>, EnvironmentalDataRepository {
    
    // 接口方法将由Spring Data JPA自动实现
    @Query("SELECT e FROM EnvironmentalData e WHERE e.sensor.id = :sensorId")
    List<EnvironmentalData> findBySensorId(Long sensorId);

    @Query("SELECT e FROM EnvironmentalData e WHERE e.sensor.location = :location")
    List<EnvironmentalData> findByLocation(String location);

    List<EnvironmentalData> findByDataType(String dataType);

    List<EnvironmentalData> findByTimestampBetween(LocalDateTime start, LocalDateTime end);

    @Query("SELECT e FROM EnvironmentalData e WHERE e.sensor.id = :sensorId AND e.dataType = :dataType ORDER BY e.timestamp DESC LIMIT :limit")
    List<EnvironmentalData> findLatestBySensorAndType(Long sensorId, String dataType, int limit);
    
    @Query("SELECT e FROM EnvironmentalData e WHERE e.sensor.id = :sensorId ORDER BY e.timestamp DESC LIMIT 1")
    EnvironmentalData findLatestBySensorId(@Param("sensorId") Long sensorId);
    
    @Query("SELECT e FROM EnvironmentalData e ORDER BY e.timestamp DESC LIMIT 1")
    EnvironmentalData getLatestEnvironmentalData();
}